//  咨询与问答 -> 图文咨询聊天列表页
//  ConsultViewController.m
//  yilutongxing
//
//  Created by ios-21 on 17/4/27.
//  Copyright © 2017年 YZE. All rights reserved.
//

#import "ConsultViewController.h"
#import "MKJChatModel.h"
#import "ConsultWriteIdeaTableViewCell.h"
#import "consultWriteIdeaView.h"
#import "PhoneConsultTableViewController.h"
#import "ConsultWriteIdealViewController.h"
#import "PicAndArticleConsultViewController.h"
#import "PlantDetailTableViewController.h"
#import "YZEDrugplanModel.h"
#import "YZEDrugplanDetailModel.h"
#import "MJExtension.h"
#import "DataUtils.h"
#import "TimeTools.h"
#import "RPUserDoctorInfo.h"
#import "YZEDoctorDetailViewController.h"

#define URL_GetChathistory @"/api/messages/%ld/historys"
#define URL_Getdoctorinfo @"/api/doctors/"
#define URL_Get

@implementation ServiceStatus
@end


@interface ConsultViewController ()<UITableViewDelegate,UITableViewDataSource,
                                    ConsultWriteIdealViewControllerDelegate, consultChatCellDelegate,
                                    consultChatCellHeadviewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataSouce;
@property (nonatomic,assign) int page;
@property (nonatomic, strong) ServiceStatus *service_status;
@property (nonatomic, strong) RPUserDoctorInfo *doctorInfo;
@end

@implementation ConsultViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = self.doctorName;
    
    self.navigationItem.hidesBackButton = YES;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"返回"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(backAction)];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    // 小技巧，用了之后不会出现多余的Cell
    UIView *view = [[UIView alloc] init];
    self.tableView.tableFooterView = view;
    
    //请求聊天记录
    self.page = 0;
    NSDictionary *pra = [NSDictionary dictionaryWithObjectsAndKeys:[[NSNumber alloc] initWithInt:self.page], @"page", @1000, @"pagesize", nil];
    [[YZENetwork sharedInstace] getRequestWithUrl:[BASE stringByAppendingFormat:URL_GetChathistory, self.doctorUID] parameters:pra delegate:self requestTag:1 successBlock:^(id responseObject) {
        //self.dataSouce = responseObject;
        for (NSDictionary *item in responseObject) {
            MKJChatModel *model = [MKJChatModel mj_objectWithKeyValues:item];
            if ([DataUtils getMyUID]==model.dSender.id) {//是自己
                model.isRight = YES;
            }
            else {
                model.isRight = NO;
            }
            [self.dataSouce addObject:model];
        }
        [self.dataSouce sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            MKJChatModel *l = obj1;
            MKJChatModel *r = obj2;
            return [TimeTools getDateWithString:l.createdDate] > [TimeTools getDateWithString:r.createdDate];
        }];
        [self.tableView reloadData];
        if (self.dataSouce.count != 0) {
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataSouce.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
        }
    }];
    
    [[YZENetwork sharedInstace] getRequestWithUrl:[BASE stringByAppendingFormat:@"%@%ld", URL_Getdoctorinfo, self.doctorID] parameters:nil delegate:self requestTag:2 successBlock:^(id responseObject) {
        self.doctorInfo = [RPUserDoctorInfo mj_objectWithKeyValuesAdd:responseObject];
        _service_status = [ServiceStatus new];
        NSNumber *canPicAsk = responseObject[@"canPicAsk"];
        if (!canPicAsk || [canPicAsk longValue]==0) {
            _service_status.is_picservice_open = NO;
        }
        else {
            _service_status.is_picservice_open = YES;
        }
        NSNumber *canPhoneAsk = responseObject[@"canTelAsk"];
        if (!canPhoneAsk || [canPhoneAsk longValue]==0) {
            _service_status.is_phoneservice_open = NO;
        }
        else {
            _service_status.is_phoneservice_open = YES;
        }
    }];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    UIView* contentView = [self.tabBarController.view.subviews objectAtIndex:0];
    contentView.backgroundColor = [UIColor blackColor];
    contentView.frame=CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT + self.tabBarController.tabBar.frame.size.height);
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = NO;
}
//返回按钮监听
- (void)backAction {
    [self dismissViewControllerAnimated:YES completion:nil];
}
//电话咨询按钮监听
- (IBAction)phoneConsult:(id)sender {
    if (!_service_status) {
        return;
    }
    else if(!_service_status.is_phoneservice_open){
        [UIView showToastWindowWithMessage:@"该医生暂时未开启电话咨询服务"];
    }
    else {
        PhoneConsultTableViewController *phone=[PhoneConsultTableViewController new];
        phone.doctorID = self.doctorID;
        UINavigationController *navi=[[UINavigationController alloc]initWithRootViewController:phone];
        [self presentViewController:navi animated:YES completion:nil];
    }
}
//图文咨询按钮监听
- (IBAction)photoConsult:(id)sender {
    if (!_service_status) {
        return;
    }
    else if(!_service_status.is_picservice_open){
        [UIView showToastWindowWithMessage:@"该医生暂时未开启图文咨询服务"];
    }
    else {
        ConsultWriteIdealViewController *vc=[ConsultWriteIdealViewController new];
        vc.delagate=self;
        vc.doctorID = self.doctorID;
        vc.doctorUID = self.doctorUID;
        UINavigationController *navi=[[UINavigationController alloc]initWithRootViewController:vc];
        [self presentViewController:navi animated:YES completion:nil];
    }
}



-(void)sendFinish:(NSDictionary*)model{
    MKJChatModel *chatModel = [MKJChatModel mj_objectWithKeyValues:model];
    //chatModel.isRight = 1; // 0 or 1
    [self.dataSouce addObject:chatModel];
    [self.tableView reloadData];
    
    if (self.dataSouce.count != 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataSouce.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
    [self.view endEditing:YES]; 
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSouce.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 定义cell标识  每个cell对应一个自己的标识
    NSString *CellIdentifier = [NSString stringWithFormat:@"cell%ld%ld",indexPath.section,indexPath.row];
    // 通过不同标识创建cell实例
    ConsultWriteIdeaTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (!cell) {
        cell = [[ConsultWriteIdeaTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        cell.delegate = self;
        MKJChatModel *model=self.dataSouce[indexPath.row];
        if (model.consultationDTO) {
            [cell refreshCellConsult:model delegate:self forIndex:indexPath.row];
        }
        if (model.suggestDTO) {
            [cell refreshCellSuggestion:model delegate:self forIndex:indexPath.row];
        }
        if (model.drugplanDTO) {
            [cell refreshCellDrugplan:model delegate:self forIndex:indexPath.row];
        }
        if (!model.consultationDTO && !model.suggestDTO && !model.drugplanDTO) {
            [cell refreshCell:model];
        }
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 150;
}

- (NSMutableArray *)dataSouce
{
    if (_dataSouce == nil) {
        _dataSouce = [[NSMutableArray alloc] init];
    }
    return _dataSouce;
}

//显示图文咨询详情
-(void)showPicAndArticleConsult:(MKJChatModel *)model{
    PicAndArticleConsultViewController *picV = [PicAndArticleConsultViewController new];
    picV.ID = model.consultationDTO._id;
    [self.navigationController pushViewController:picV animated:YES];
}
//显示咨询建议详情
-(void)showSuggestion:(MKJChatModel *)model{
    PicAndArticleConsultViewController *picV = [PicAndArticleConsultViewController new];
    picV.ID = 2;
    [self.navigationController pushViewController:picV animated:YES];
}
//显示用药方案详情
-(void)showDrugplan:(MKJChatModel *)model{
    PlantDetailTableViewController *drugplanV = [PlantDetailTableViewController new];
    drugplanV.drugplan = model.drugplanDTO;
    [self.navigationController pushViewController:drugplanV animated:YES];
}

#pragma mark - consultChatCellDelegate
- (void)onTapCellforIndex:(NSUInteger)index{
    MKJChatModel *model = self.dataSouce[index];
    if (model.consultationDTO) {
        [self showPicAndArticleConsult:model];
    }
    else if(model.suggestDTO){
        [self showSuggestion:model];
    }
    else if(model.drugplanDTO){
        [self showDrugplan:model];
    }
}

#pragma mark - consultChatCellHeadviewDelegate
- (void)onHeadViewTaped{
    YZEDoctorDetailViewController *v = [YZEDoctorDetailViewController new];
    v.data = self.doctorInfo;
    UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:v];
    [self presentViewController:navi animated:YES completion:nil];
}

@end
